package com.kaidongyuan.app.kdydriverr.ui.activity;
import cn.jpush.android.api.JPushInterface;

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Looper;
import android.os.Vibrator;
import android.os.StrictMode;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.JsResult;
import android.webkit.PermissionRequest;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.location.LocationClient;
import com.codec.binary.StringUtils;
import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
import com.kaidongyuan.app.basemodule.utils.nomalutils.MPermissionsUtil;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.design.widget.Snackbar;
import android.support.v4.content.FileProvider;
import android.view.Gravity;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;
import static android.widget.Toast.LENGTH_LONG;

import android.media.MediaPlayer;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.kaidongyuan.app.basemodule.interfaces.AsyncHttpCallback;
import com.kaidongyuan.app.basemodule.utils.nomalutils.NetworkUtils;
import com.kaidongyuan.app.basemodule.widget.MLog;
import com.kaidongyuan.app.kdydriverr.R;
import com.kaidongyuan.app.kdydriverr.app.AppContext;
import com.kaidongyuan.app.kdydriverr.bean.Tools;
import com.kaidongyuan.app.kdydriverr.constants.Constants;
import com.kaidongyuan.app.kdydriverr.httpclient.OrderAsyncHttpClient;
import com.kaidongyuan.app.kdydriverr.serviceAndReceiver.CameraManager;
import com.kaidongyuan.app.kdydriverr.serviceAndReceiver.TrackingService;
import com.kaidongyuan.app.kdydriverr.serviceAndReceiver.VueTrackingScanService;
import com.kaidongyuan.app.kdydriverr.ui.base.BaseFragmentActivity;
import com.kaidongyuan.app.kdydriverr.ui.base.ScanCodeBroadcastReceiver;
import com.kaidongyuan.app.kdydriverr.utils.AES256Utils;
//import com.kaidongyuan.app.kdydriver.utils.AES256Utilsok;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import cpcl.PrinterHelper;

import java.util.ArrayList;
import java.util.List;
import com.snbc.sdk.LabelPrinter;


import android.bluetooth.BluetoothAdapter;
public class hbx extends BaseFragmentActivity implements AsyncHttpCallback {

    public static Context mContext;
    public static WebView mWebView;
    static {
        System.loadLibrary("LabelPrinterSDK");
    }
    String inputName;
    String inputName1;
    public String ScanResultP;
    public static final int REQUEST_READ_PHONE_STATE = 8;

    String appName;
    String requestCodeVal;
    String ifManualUpdate = "更新";

    public static String mAppVersion;

    // 微信开放平台APP_ID
    private static final String APP_ID = Constants.WXLogin_AppID;

    static public IWXAPI mWxApi;

    public final static String DestFileName = "hyjt.apk";
    public final static String ZipFileName = "dist.zip";

    String server_App_Version;

    String server_App_Url;

    //检测版本更新
    private final String TAG_CHECKVERSION = "check_version";
    private OrderAsyncHttpClient mClient;
    private NotificationManager mNotificationManager;
    private Handler mHandler;
    private Notification mUpdataNotification;
    private Snackbar pmSnackbar;
    private RemoteViews remoteView;
    private final int RequestPermission_STATUS_CODE0=8800;
    private AlertDialog mUpdataVersionDialog;

    //5.0以下使用
    private ValueCallback<Uri> uploadMessage;
    // 5.0及以上使用
    private ValueCallback<Uri[]> uploadMessageAboveL;
    //图片
    private final static int FILE_CHOOSER_RESULT_CODE = 128;
    //拍照
    private Uri cameraFielUri;
    private final static int FILE_CAMERA_RESULT_CODE = 129;
    //拍照图片路径
    private String cameraFielPath;
    private Uri mImageUri, mImageUriFromFile;
    private static final String FILE_PROVIDER_AUTHORITY = "com.cy_scm.android_sxjf2.fileprovider";
    //    private String CURR_ZIP_VERSION = "99.9.9";
    private String CURR_ZIP_VERSION = "0.2.60";

    private Intent mLocationIntent;
    private Intent mVueLocationIntent;

    private CaptureManager capture;
    private DecoratedBarcodeView barcodeScannerView;
    RelativeLayout scan_rt;  // 扫码控件布局

    ScanCodeBroadcastReceiver scanCodeBroadcastReceiver;
    private CameraManager mCameraManager;
    // 震动
    private Vibrator Vibrator;

    private BluetoothAdapter myBluetoothAdapter;
    // 打印机设置字段---------------开始
    LabelPrinter labelPrinter;
    //打印机名字和地址
    private String tagPrinterName = null;
    private String tagPrinterAddress = null;
    private String orderPrinterName = null;
    private String orderPrinterAddress = null;
    public int nReturn;
    public int nReturnPrint;
    private String barLable = null;
    private String orderInfo = null;

    private String imageChooserType = "all";

    static final String[] PERMISSION = new String[]{
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_CALL_LOG,
    };
    List<String> lstDevices = new ArrayList<String>();

    private static final String SCANACTION = "com.android.scanservice.scancontext";

    // 打印机设置字段---------------结束
    @SuppressLint("JavascriptInterface")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setPermissions();
        setContentView(R.layout.scan);
        mContext = this;
        nReturn = 0;
        nReturnPrint = 0;
        // 进入系统访问打开蓝牙设备
        myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (myBluetoothAdapter == null) {
            return;
        } else if (!myBluetoothAdapter.isEnabled()) {
            // 打开蓝牙
            myBluetoothAdapter.enable();
        }

        //拍照功能
        mCameraManager = new CameraManager(this, null);


        //注册PDA扫码事件 开始
        scanCodeBroadcastReceiver = new ScanCodeBroadcastReceiver(this, mCameraManager);
        IntentFilter intentFilter2 = new IntentFilter();
        intentFilter2.addAction("com.android.scanservice.scancontext");
        intentFilter2.addAction("com.android.server.scannerservice.broadcast");
        intentFilter2.addAction("android.intent.ACTION_DECODE_DATA");
        intentFilter2.addAction("android.intent.action.SCANRESULT");
        registerReceiver(scanCodeBroadcastReceiver, intentFilter2);
        //注册PDA扫码事件 结束

        barcodeScannerView = (DecoratedBarcodeView) findViewById(R.id.dbv_custom);

        capture = new CaptureManager(this, barcodeScannerView);
        capture.initializeFromIntent(getIntent(), savedInstanceState);

        scan_rt = (RelativeLayout) findViewById(R.id.scan_rt);

        android.view.ViewGroup.LayoutParams pp = scan_rt.getLayoutParams();

        Resources resources = this.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
//        float density1 = dm.density;
//        int width3 = dm.widthPixels;
        int height3 = dm.heightPixels;
        //标准宽度 720  高度348

        Log.d("LM", "屏幕高度: " + height3);

        //  扫码框高度设置
        pp.height = height3*160/1280;
        scan_rt.setLayoutParams(pp);

        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) scan_rt.getLayoutParams();
        lp.topMargin = height3*80/1280;
        scan_rt.setLayoutParams(lp);

        scan_rt.setVisibility(View.INVISIBLE);
        capture.onPause();
        requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
        requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        requestPermission(Manifest.permission.RECORD_AUDIO);
        verifyAudioPermissions(this);
        ActivityCompat.requestPermissions(this,PERMISSION,1);
        requestReadPhonePermission();
//        boolOpenCarmer();
//        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
//
//        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
//        } else {
//            //TODO
//        }

        try {
            mAppVersion = getMContext().getPackageManager().getPackageInfo(getMContext().getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        Log.d("LM", "程序启动");


        //解决安卓7.0手机拍照闪退的问题
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            builder.detectFileUriExposure();
        }

        // 设置ZIP版本号
        String curr_zip_version = Tools.getAppZipVersion(mContext);

        if(curr_zip_version != null && curr_zip_version.equals("")) {

            Tools.setAppZipVersion(mContext, CURR_ZIP_VERSION);
        }

        curr_zip_version = Tools.getAppZipVersion(mContext);

        LocationClient mLocationClient = new LocationClient(getApplicationContext());
//        LocationClient mVueLocationClient = new LocationClient(getApplicationContext());

        appName = getResources().getString(R.string.app_name);

        mWebView = (WebView) findViewById((R.id.lmwebview));
        mWebView.getSettings().setTextZoom(100);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
            mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        }else{
            try {
                Class<?> clazz = mWebView.getSettings().getClass();
                Method method = clazz.getMethod("setAllowUniversalAccessFromFileURLs", boolean.class);
                if (method != null) {
                    method.invoke(mWebView.getSettings(), true);
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        mWebView.setWebViewClient(new WebViewClient() {
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.d("LM", "当前位置: " + url);
            }

            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

            }

            // js拔打电话
            @Override
            public boolean shouldOverrideUrlLoading(WebView view,String url) {
                Log.d("LM", "------------------------: ");

                if (url.startsWith("mailto:") || url.startsWith("geo:") || url.startsWith("tel:")) {

                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                }
                return true;
            }
        });

        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        mWebView.setWebChromeClient(new WebChromeClient() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onPermissionRequest(PermissionRequest request) {
                request.grant(request.getResources());
            }

            public void onProgressChanged(WebView view, int newProgress) {
                //bugly Javascript的异常捕获功能
                CrashReport.setJavascriptMonitor(view, true);

                super.onProgressChanged(view, newProgress);
            }

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> valueCallback) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android  >= 3.0
            public void openFileChooser(ValueCallback valueCallback, String acceptType) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            //For Android  >= 4.1
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android >= 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;
                openImageChooserActivity();
                return true;
            }

            // 处理javascript中的alert
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                return false;
            }

            // 处理javascript中的confirm
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                return true;
            }

            // 处理定位权限请求
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
                Log.d("LM", "处理定位权限请求：：ddd ");
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }

            // 设置应用程序的标题title
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }
        });

        mLocationClient.start();
//        mVueLocationClient.start();

        // 获取上次启动记录的版本号
        String lastVersion = Tools.getAppLastTimeVersion(mContext);

        mWebView.loadUrl("file:///android_asset/apps/H5A4057B2/www/index.html");

        Tools.setAppLastTimeVersion(mContext);

        lastVersion = Tools.getAppLastTimeVersion(mContext);

        // 启用javascript
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setVerticalScrollbarOverlay(true);

        // 在js中调用本地java方法
        mWebView.addJavascriptInterface(new JsInterface(this), "CallAndroidOrIOS");

        mWebView.setLongClickable(true);
        mWebView.setScrollbarFadingEnabled(true);
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.setDrawingCacheEnabled(true);

        WebSettings settings = mWebView.getSettings();
        settings.setDomStorageEnabled(true);


//        minefragment = new MineFragment();
        mClient = new OrderAsyncHttpClient(this, this);
        mNotificationManager = (NotificationManager) getMContext().getSystemService(Context.NOTIFICATION_SERVICE);
        initPermission();
//        boolOpenCarmer();

        //开启后台定位服务
        if (mLocationIntent == null) {
            mLocationIntent = new Intent(this, TrackingService.class);
        }
        getApplicationContext().startService(mLocationIntent);
        initHandler();
        initJPush();

        capture.setResultCallBack(new CaptureManager.ResultCallBack() {
            @Override
            public void callBack(int requestCode, int resultCode, Intent intent) {
                IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
                if (null != result && null != result.getContents()) {
                    showDialog(result.getContents());


                    //扫描页面上面的扫描二维码页面，如果没有显示，就不调用后面的拉起扫描
//                    if(scan_rt != null && scan_rt.getVisibility() != View.VISIBLE){
//                        return;
//                    }

                    new Thread() {
                        public void run() {
                            try {
                                sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    // 重新拉起扫描
                                    capture.onResume();
                                    capture.decode();
                                }
                            });
                        }
                    }.start();
                }
            }
        });
        capture.decode();
    }

    /**
     * 获取所有已配对的设备
     */
    public static List<BluetoothDevice> getPairedDevices() {
        List deviceList = new ArrayList<>();
        Set<BluetoothDevice> pairedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                deviceList.add(device);
            }
        }
        return deviceList;
    }
    //    打印机设置代码--结束

    public void showDialog(String result) {
        // 弹出dialog的代码略...

        Log.d("LM", result);

        String url = "javascript:QRScanAjax('" + result + "')";
        hbx.mWebView.loadUrl(url);

    }

    private void requestReadPhonePermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            //在这里面处理需要权限的代码
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_READ_PHONE_STATE);
        }
    }
    private void requestPermission(String permission) {
        if(ContextCompat.checkSelfPermission(this, permission)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, new String[]{permission}, 0);
        }
    }
    //申请录音权限
    private static final int GET_RECODE_AUDIO = 1;
    private static String[] PERMISSION_AUDIO = {
            Manifest.permission.RECORD_AUDIO
    };
    /*
     * 申请录音权限*/
    public static void verifyAudioPermissions(Activity activity) {
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.RECORD_AUDIO);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, PERMISSION_AUDIO,
                    GET_RECODE_AUDIO);
        }
    }
    private void boolOpenCarmer(){
//READ_PHONE_STATE   CALL_PHONE
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)  //打开相机权限
                != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)   //可读
                        != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)  //可写
                        != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                        != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED||
                ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED||
                ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS)
                        != PackageManager.PERMISSION_GRANTED||
                ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
                        != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_PHONE_STATE,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.CALL_PHONE},
                    REQUEST_READ_PHONE_STATE);
        }else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_READ_PHONE_STATE);
        }
    }

    @Override
    public void postSuccessMsg(String msg, String request_tag) {

        Log.d("LM", "标签" + request_tag + "请求成功：" + msg);

        if (msg.equals("error")){
            //下载安装包失败
            if (request_tag.equals(DestFileName)){
                Message message=mHandler.obtainMessage();
                message.arg1=-1;
                message.sendToTarget();
                return;
            }

            if (!NetworkUtils.isNetworkAvailable(getMContext())){
                NetworkUtils.setContactNetDialog(getApplication());
                return;
            }
        }else if (request_tag.equals(TAG_CHECKVERSION)){

            JSONObject result = null;

            JSONObject jo= JSON.parseObject(msg);

            try {
                result = JSON.parseObject(new String(AES256Utils.base64Decode(jo.getString("result"))));

            } catch (Exception e) {
                e.printStackTrace();
            }
            String status = result.getString("code");

            String apkDownloadUrl = null;
            String server_apkVersion = null;
            if(status.equals("0")) {
                //JSONObject dict = JSON.parseObject(AES256Utils.decrypt(Constants.SecretKey,jo.getString("data")));
                JSONObject dict = null;
                try {
                    dict = result.getJSONObject("entity");
                    apkDownloadUrl = dict.getString("downloadUrl");
                    server_apkVersion = dict.getString("versionNo");

                    Log.d("LM", "服务器下载地址：" + apkDownloadUrl + "；版本号：" + server_apkVersion);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (server_apkVersion!=null && apkDownloadUrl!=null) {
                try {
                    String current_apkVersion = mAppVersion;
                    MLog.w( "server_apkVersion:"+server_apkVersion+"\tcurrent_apkVersion:"+current_apkVersion);

                    int compareVersion = Tools.compareVersion(server_apkVersion, current_apkVersion);

                    if (compareVersion == 1) {

                        createUpdateDialog(current_apkVersion, server_apkVersion, apkDownloadUrl);
                    } else {

                        if(ifManualUpdate.equals("手动更新")){

                            AlertDialog.Builder builderw = new AlertDialog.Builder(mContext);
//                            builderw.setTitle("更新版本");
                            builderw.setMessage("当前版本为最新版本");
                            builderw.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    mUpdataVersionDialog.cancel();
                                }
                            });
                            builderw.setCancelable(false);

                            mUpdataVersionDialog = builderw.create();
                            mUpdataVersionDialog.show();

                            ifManualUpdate = "更新";
                        }else{
                            Log.d("LM", "apk为最新版本");
                            checkGpsState();
                        }
                    }
                } catch (Exception e) {
                    Log.d("LM","NameNotFoundException" + e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 版本更新对话框
     * @param currentVersion 当前版本versionName
     * @param version 最新版本versionName
     * @param downUrl 最新版本安装包下载url
     */
    public void createUpdateDialog(String currentVersion, String version, final String downUrl) {

        mClient = new OrderAsyncHttpClient(this, this);

        AlertDialog.Builder builderw = new AlertDialog.Builder(mContext);
        builderw.setTitle("更新版本");
        builderw.setMessage("当前版本：" + currentVersion + "\n最新版本：" + version);
        builderw.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mUpdataVersionDialog.cancel();
            }
        });
        builderw.setNegativeButton("下载", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                mUpdataVersionDialog.cancel();
                MLog.w("update.url:" + downUrl);
                //以存储文件名为Tag名
                mClient.sendFileRequest(downUrl, DestFileName);
            }
        });
        builderw.setCancelable(false);
//        builder.show();
        mUpdataVersionDialog = builderw.create();
        mUpdataVersionDialog.show();
    }


    /**
     * 判断 GPS是否开启
     */
    private void checkGpsState() {
        LocationManager alm= (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if( !alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER )&&!alm.isProviderEnabled(LocationManager.NETWORK_PROVIDER) ) {
            MLog.w("MainActivity.checkGpsState:GpsisOff");
            createCheckGpsDialog();
        } else {
            MLog.w("MainActivity.checkGpsState:GpsisOn");
        }
    }
    //    checkPermissionGranted(Manifest.permission.ACCESS_FINE_LOCATION)
//    checkPermissionGranted(Manifest.permission.ACCESS_COARSE_LOCATION)
// private boolean checkPermissionGranted(String permission) {
//             return this.checkPermission(permission, Process.myPid(), Process.myUid()) == PackageManager.PERMISSION_GRANTED;
//}
//    openGpsStateVue
    private void openGpsStateVue() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_READ_PHONE_STATE);
    }
    /**
     * 判断 GPS是否开启
     */
    private void checkGpsStateVue() {
        Log.d("LM", "ACCESS_FINE_LOCATION的值是" + ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION));
        Log.d("LM", "ACCESS_COARSE_LOCATION的值是" + ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION));
        Log.d("LM", "PackageManager.PERMISSION_GRANTED的值是" + PackageManager.PERMISSION_GRANTED);

        LocationManager alm= (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if( !(alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER )&&alm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)&&(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)&&(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) )) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.d("LM", "no没获取到位置权限");
                    MLog.w("MainActivity.checkGpsStateVue:GpsisOff");
                    String url = "javascript:checkGpsState(true)";
                    mWebView.loadUrl(url);
                }
            });
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.d("LM", "yes获取到位置权限了");
                    String url = "javascript:checkGpsState()";
                    mWebView.loadUrl(url);
                    MLog.w("MainActivity.checkGpsStateVue:GpsisOn");
                }
            });
        }
    }

    private void createCheckGpsDialog() {
        showSnackbar("请开启GPS服务", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent myIntent;
                myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                hbx.this.startActivity(myIntent);
            }
        }, Snackbar.LENGTH_INDEFINITE);
    }

    private void showSnackbar(String strSnackbar, View.OnClickListener listener,int duration) {
        pmSnackbar = Snackbar.make(findViewById(R.id.acitvity_mainAcitivity),strSnackbar,duration);
        View v= pmSnackbar.getView();
        v.setBackgroundColor(getResources().getColor(R.color.details_text));
        final TextView tv_snackbar= (TextView) v.findViewById(R.id.snackbar_text);
        tv_snackbar.setGravity(Gravity.CENTER);
        tv_snackbar.setTextColor(getResources().getColor(R.color.white));
        pmSnackbar.setAction("设置",listener).show();
    }

    // js调用java
    private class JsInterface extends Activity {
        private Context mContext;

        public JsInterface(Context context) {
            this.mContext = context;
        }

        @JavascriptInterface
        public void callAndroidTrack(String u, String p) {

            // 当前时间
            String curDate = Tools.getCurrDate();

            if (u != null) {

                Log.d("LM", "保存轨迹的手机号" + u);
                SharedPreferences crearPre = mContext.getSharedPreferences("w_UserInfo", MODE_PRIVATE);
                crearPre.edit().putString("UserName", u).commit();
                crearPre.edit().putString("Password", p).commit();
                crearPre.edit().putString("Set_User_Pass_Time", curDate).commit();
            }
        }

        @JavascriptInterface
        public void callAndroid( String exceName,final String inputName) {
            hbx.this.inputName = inputName;
            if (exceName.equals("登录页面已加载")) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        String  url = "javascript:VersionShow('" + Tools.getVerName(mContext) + "')";
                        hbx.mWebView.loadUrl(url);
                        Log.d("LM", url);

                        url = "javascript:Device_Ajax('android')";
                        hbx.mWebView.loadUrl(url);
                        Log.d("LM", url);
                    }
                });
            } else if (exceName.equals("获取当前位置页面已加载")) {

                Log.d("LM", "获取当前位置页面已加载");

                new Thread() {
                    public void run() {
                        //开启后台定位服务
                        mVueLocationIntent = new Intent(mContext, VueTrackingScanService.class);
                        mContext.getApplicationContext().startService(mVueLocationIntent);

                    }
                }.start();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //延迟两秒
                        try {
                            Thread.sleep( 1500 );
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        SharedPreferences readLatLng = mContext.getSharedPreferences("vueCurrLatLng", MODE_MULTI_PROCESS);

                        final String address = readLatLng.getString("vue_w_address", "");
                        final String lng = readLatLng.getString("vue_w_lng","");
                        final String lat = readLatLng.getString("vue_w_lat", "");

                        JSONObject lngObject =  new JSONObject();
                        lngObject.put("lng",lng);
                        lngObject.put("lat",lat);

                        String url = "javascript:SetCurrAddress('" + lngObject + "')";

                        hbx.mWebView.loadUrl(url);
                    }
                });
            } else if (exceName.equals("导航")) {

                new Thread() {

                    public void run() {

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                Tools.ToNavigation(hbx.this.inputName, mContext, appName);
                            }
                        });
                    }
                }.start();

            } else if (exceName.equals("查看路线")) {

                Log.d("LM", "查看路线");

                new Thread() {

                    public void run() {

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                Intent intent2=new Intent(mContext,OrderTrackActivity.class);
                                intent2.putExtra("order_IDX",hbx.this.inputName);
                                mContext.startActivity(intent2);
                            }
                        });
                    }
                }.start();
            }else if(exceName.equals("顺店通打印")){

                Intent intentprint3=new Intent(mContext,AdEscPrint.class);
                intentprint3.putExtra("Authorization",hbx.this.inputName);
                mContext.startActivity(intentprint3);
            }else if(exceName.equals("打印")){

                Intent intentprint=new Intent(mContext,PrintActivity.class);
                intentprint.putExtra("omsNo",hbx.this.inputName);
                mContext.startActivity(intentprint);

            }else if(exceName.equals("shein打印")){

                Log.d("LM", "shein打印");

                Intent intentprint1=new Intent(mContext,PrintActivityshein.class);
                intentprint1.putExtra("omsNo",hbx.this.inputName);
                mContext.startActivity(intentprint1);
            }else if(exceName.equals("航空标签打印")){

                Log.d("LM", "航空标签打印");

                Intent intentprint2=new Intent(mContext,AirLabelPrinting.class);
                intentprint2.putExtra("omsNo",hbx.this.inputName);
                mContext.startActivity(intentprint2);
            }else if(exceName.equals("检查位置权限")){
                checkGpsStateVue();
            }else if(exceName.equals("位置权限")){
                openGpsStateVue();
            }else if(exceName.equals("连接蓝牙")){
//                myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//                if (myBluetoothAdapter == null) {
//                    return;
//                } else if (!myBluetoothAdapter.isEnabled()) {
//                    // 打开蓝牙
//                    myBluetoothAdapter.enable();
//                }
//                try{
//                    if (LABEL.equals(hbx.this.inputName)) {
//                        PrinterHelper.portClose();
//                    }
//                    int nNum = 0;
//                    labelPrinter = new LabelPrinter();
//                    Log.d("LM", "00000000000000000000000000000000000");
//
//                    final List<BluetoothDevice> pairedDevices = getPairedDevices();
//                    final String[] deviceNames = new String[pairedDevices.size() + 1];
//                    for (int i = 0; i < pairedDevices.size(); i++) {
//                        deviceNames[i] = pairedDevices.get(i).getName();
//                    }
//                    deviceNames[pairedDevices.size()] = "配对更多设备";
//
//                    AlertDialog.Builder listDialog = new AlertDialog.Builder(hbx.this, AlertDialog.THEME_DEVICE_DEFAULT_DARK);
//
//                    listDialog.setTitle("打印机列表:");
//                    listDialog.setItems(deviceNames, new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            if (deviceNames.length - 1 == which) {
//                                startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
//                            } else {
//                                tagPrinterName = deviceNames[which];
//                                tagPrinterAddress = pairedDevices.get(which).getAddress();
//                                if (LABEL.equals(hbx.this.inputName)) { // 标签打印连接设备
//                                    try{
//                                        Log.d("LM", "00000000000000000000" + tagPrinterAddress);
//                                        Log.d("LM", "00000000000000000000" + tagPrinterName);
//                                        int portOpen = PrinterHelper.portOpenBT(mContext.getApplicationContext(), tagPrinterAddress);
//                                        if (portOpen == 0) {
//                                            AlertDialog.Builder builderw1 = new AlertDialog.Builder(mContext);
//                                            builderw1.setTitle("提示");
//                                            builderw1.setMessage("打印机连接成功");
//                                            builderw1.show();
//                                        }
//                                        if (portOpen == -1) {
//                                            AlertDialog.Builder builderw1 = new AlertDialog.Builder(mContext);
//                                            builderw1.setTitle("提示");
//                                            builderw1.setMessage("打印机连接超时");
//                                            builderw1.show();
//                                        }
//                                        if (portOpen == -2) {
//                                            AlertDialog.Builder builderw2 = new AlertDialog.Builder(mContext);
//                                            builderw2.setTitle("提示");
//                                            builderw2.setMessage("蓝⽛地址格式错误");
//                                            builderw2.show();
//                                        }
//                                        if (portOpen == -3) {
//                                            AlertDialog.Builder builderw3 = new AlertDialog.Builder(mContext);
//                                            builderw3.setTitle("提示");
//                                            builderw3.setMessage("打印机与SDK不匹配（握⼿不通过）");
//                                            builderw3.show();
//                                        }
//                                    }catch (Exception e){
//                                        e.printStackTrace();
//                                    }
//                                }
//                                if (ORDER.equals(hbx.this.inputName)) { // 入库 order信息打印连接设备
//
//                                    nReturn = labelPrinter.ConnectPrinter(7, tagPrinterAddress, 2);
//                                    if (nReturn == 0) {
//                                        AlertDialog.Builder builderw1 = new AlertDialog.Builder(mContext);
//                                        builderw1.setTitle("提示");
//                                        builderw1.setMessage("打印机连接成功");
//                                        builderw1.show();
//                                    }else {
//                                        AlertDialog.Builder builderw1 = new AlertDialog.Builder(mContext);
//                                        builderw1.setTitle("提示");
//                                        builderw1.setMessage("打印机连接失败");
//                                        builderw1.show();
//                                    }
//                                }
//                            }
//                        }
//                    });
//                    listDialog.show();
//                    return;
//                }catch (Exception e){
//                    Log.e("SDKSample", (new StringBuilder("Activity_Main --> onClickClose ")).append(e.getMessage()).toString());
//                }
            }
        }

        @JavascriptInterface
        public void getImageChooserType(String code){
            imageChooserType = code;
        }
        private String LABEL = "label";
        private String ORDER = "order";
        // 设备连接蓝牙
        @JavascriptInterface
        public void ReconnectLanYa(String info){
            JSONObject macInfo = JSON.parseObject(info);
            final String flag = macInfo.getString("type");
            String mac = macInfo.getString("mac");
            myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (myBluetoothAdapter == null) {
                return;
            } else if (!myBluetoothAdapter.isEnabled()) {
                // 打开蓝牙
                myBluetoothAdapter.enable();
            }
            try{
                if (LABEL.equals(flag)) {
                    PrinterHelper.portClose();
                }
//                if (ORDER.equals(flag)) {
//                    Log.d("LM", "11111111111111111" + flag);
//                    labelPrinter = new LabelPrinter();
//                    labelPrinter.Disconnect();
//                }
                int nNum = 0;
                labelPrinter = new LabelPrinter();

                final List<BluetoothDevice> pairedDevices = getPairedDevices();
                final String[] deviceNames = new String[pairedDevices.size() + 1];
                for (int i = 0; i < pairedDevices.size(); i++) {
                    deviceNames[i] = pairedDevices.get(i).getName();
                    if (StringUtils.equals(mac, pairedDevices.get(i).toString())) {
                        if (LABEL.equals(flag)) {
                            try {
                                int portOpen = PrinterHelper.portOpenBT(mContext.getApplicationContext(), mac);
                                if (portOpen == 0) {
                                    showToastMsg("打印机连接成功",2000);
                                } else {
                                    showToastMsg("打印机连接失败，请重新连接",2000);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        if (ORDER.equals(flag)) { // 入库 order信息打印连接设备
                            nReturn = labelPrinter.ConnectPrinter(7, mac, 2);
                            if (nReturn == 0) {
                                showToastMsg("打印机连接成功",2000);
                            }else {
                                showToastMsg("打印机连接失败，请重新连接",2000);
                            }
                        }
                        return;
                    }
                }
                deviceNames[pairedDevices.size()] = "配对更多设备";

                AlertDialog.Builder listDialog = new AlertDialog.Builder(hbx.this, AlertDialog.THEME_DEVICE_DEFAULT_DARK);

                listDialog.setTitle("打印机列表:");
                listDialog.setItems(deviceNames, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (deviceNames.length - 1 == which) {
                            Intent autoIntent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
                            mContext.startActivity(autoIntent);
                        } else {
                            tagPrinterName = deviceNames[which];
                            tagPrinterAddress = pairedDevices.get(which).getAddress();
                            if (LABEL.equals(flag)) { // 标签打印连接设备
                                try{
                                    int portOpen = PrinterHelper.portOpenBT(mContext.getApplicationContext(), tagPrinterAddress);
                                    if (portOpen == 0) {
                                        // 回传打印机信息给H5
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                String  url = "javascript:LanYaMac('" + tagPrinterName + "', '" + tagPrinterAddress + "')";
                                                hbx.mWebView.loadUrl(url);
                                            }
                                        });
                                        AlertDialog.Builder builderw1 = new AlertDialog.Builder(mContext);
                                        builderw1.setTitle("提示");
                                        builderw1.setMessage("打印机连接成功");
                                        builderw1.show();
                                    }
                                    if (portOpen == -1) {
                                        AlertDialog.Builder builderw1 = new AlertDialog.Builder(mContext);
                                        builderw1.setTitle("提示");
                                        builderw1.setMessage("打印机连接超时");
                                        builderw1.show();
                                    }
                                    if (portOpen == -2) {
                                        AlertDialog.Builder builderw2 = new AlertDialog.Builder(mContext);
                                        builderw2.setTitle("提示");
                                        builderw2.setMessage("蓝⽛地址格式错误");
                                        builderw2.show();
                                    }
                                    if (portOpen == -3) {
                                        AlertDialog.Builder builderw3 = new AlertDialog.Builder(mContext);
                                        builderw3.setTitle("提示");
                                        builderw3.setMessage("打印机与SDK不匹配（握⼿不通过）");
                                        builderw3.show();
                                    }
                                }catch (Exception e){
                                    e.printStackTrace();
                                }
                            }
                            if (ORDER.equals(flag)) { // 入库 order信息打印连接设备

                                nReturn = labelPrinter.ConnectPrinter(7, tagPrinterAddress, 2);
                                if (nReturn == 0) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            String  url2 = "javascript:LanYaMac2('" + tagPrinterName + "', '" + tagPrinterAddress + "')";
                                            hbx.mWebView.loadUrl(url2);
                                        }
                                    });
                                    AlertDialog.Builder builderw1 = new AlertDialog.Builder(mContext);
                                    builderw1.setTitle("提示");
                                    builderw1.setMessage("打印机连接成功");
                                    builderw1.show();
                                }else {
                                    AlertDialog.Builder builderw1 = new AlertDialog.Builder(mContext);
                                    builderw1.setTitle("提示");
                                    builderw1.setMessage("打印机连接失败");
                                    builderw1.show();
                                }
                            }
                        }
                    }
                });
                listDialog.show();
                return;
            }catch (Exception e){
                Log.e("SDKSample", (new StringBuilder("Activity_Main --> onClickClose ")).append(e.getMessage()).toString());
            }
        }
        // 打印条形码
        @JavascriptInterface
        public void CustomerBarCode(String params){
            JSONObject info = JSON.parseObject(params);
            String clientOrderNo =  info.getString("clientOrderNo");
            String orderQty = info.getString("orderQty");
            try
            {
                PrinterHelper.printAreaSize("0", "200", "200", "840", "1");
                PrinterHelper.PageWidth("608");
                PrinterHelper.Barcode(PrinterHelper.BARCODE, "128", "2", "1", "80", "100", "100", true, "4", "50", "5", clientOrderNo);
                PrinterHelper.SetBold("1"); //对下⾯的字体进⾏加粗（如不需要加粗不⽤添加）
                PrinterHelper.Text(PrinterHelper.TEXT, "7", "0", "250", "270", orderQty);
                PrinterHelper.SetBold("0"); //关闭加粗
                PrinterHelper.Form();
                PrinterHelper.Print();
            }
            catch (Exception e)
            {
                AlertDialog.Builder builderw4 = new AlertDialog.Builder(mContext);
                builderw4.setTitle("提示");
                builderw4.setMessage("打印失败" + (new StringBuilder("Activity_1DBarcodes --> onClickPrint ")).append(e.getMessage()).toString());
                builderw4.show();
            }
        }
        // 打印条形码
        @JavascriptInterface
        public void LogBarCode(String code){
            barLable = code;
            try
            {
                PrinterHelper.printAreaSize("0", "200", "200", "840", "1");
                PrinterHelper.PageWidth("608");
                PrinterHelper.Barcode(PrinterHelper.BARCODE, "128", "2", "1", "80", "80", "100", true, "4", "50", "5", barLable);
                PrinterHelper.Print();
            }
            catch (Exception e)
            {
                AlertDialog.Builder builderw4 = new AlertDialog.Builder(mContext);
                builderw4.setTitle("提示");
                builderw4.setMessage("打印失败" + (new StringBuilder("Activity_1DBarcodes --> onClickPrint ")).append(e.getMessage()).toString());
                builderw4.show();
            }
        }

        // 入库扫描后打印面单  森
        @JavascriptInterface
        public void printOrder(String params){
            orderInfo = params;
            nReturnPrint = printFun();
            if (nReturnPrint == 0) {
                Log.d("LM", "打印成功");
//                AlertDialog.Builder builderw4 = new AlertDialog.Builder(mContext);
//                builderw4.setTitle("提示");
//                builderw4.setMessage("打印成功");
//                builderw4.show();
            }else{
                Log.d("LM", "打印失败");
                AlertDialog.Builder builderw4 = new AlertDialog.Builder(mContext);
                builderw4.setTitle("提示");
                builderw4.setMessage("打印失败" + requestCodeVal);
                builderw4.show();
            }
        }
        public int printFun(){
            JSONObject jo = JSON.parseObject(orderInfo);
            labelPrinter.SetPrintMode(1, 120);
            labelPrinter.SetPrintSpeed(14);
            int r = labelPrinter.SetLabelSize(640, 480);
            if (r != 0) {
                return r;
            }
            String font = "SIMSUN.TTF";

            String labelNo2 = jo.getString("labelNo"); //单号
            String omsNo = jo.getString("omsNo");  //格口
//            String loc = jo.getString("loc");  //线体
//            String qty = "数量：" + jo.getString("qty");
//            String ydq = jo.getString("ydq");

            labelPrinter.PrintText(245, 200, font, omsNo, 0, 100, 100, 2);
//            labelPrinter.PrintBarcodeQR(70, 250, 0, labelNo2, 'H', 4, 2);
            labelPrinter.PrintBarcodeQR(30, 130, 0, labelNo2, 'H', 8, 2);

//            labelPrinter.PrintText(330, 30, font, labelNo2, 0, 20, 20, 2);
//            labelPrinter.PrintText(85, 210, font, loc,  0, 80, 80, 2);
//            char[] chars = ydq.toCharArray();
//            int y = 110;
//            for (int i=0;i< chars.length;i++){
//                Log.d("LM", "000" + chars[i]+"");
//                labelPrinter.PrintText(520, y + i * 40, font, chars[i]+"",  0, 50, 50, 2);
//            }
//
//            labelPrinter.PrintText(30, 420, font, qty,  0, 30, 30, 2);
            r = labelPrinter.PrintLabel(1, 1);
            if (r != 0) {
                switch (r) {
                    case 1:
                        requestCodeVal = "无效的句柄";
                        break;
                    case 2:
                        requestCodeVal = "无效的参数";
                        break;
                    case 3:
                        requestCodeVal = "通讯错误";
                        break;
                    case 4:
                        requestCodeVal = "加载动态库失败";
                        break;
                    case 5:
                        requestCodeVal = "打开/创建文件失败";
                        break;
                    case 6:
                        requestCodeVal = "无效的路径";
                        break;
                    case 7:
                        requestCodeVal = "文件操作失败";
                        break;
                    case 8:
                        requestCodeVal = "内存操作失败";
                        break;
                    case 9:
                        requestCodeVal = "无效的内存";
                        break;
                    case 10:
                        requestCodeVal = "开辟的内存不足";
                        break;
                    case 11:
                        requestCodeVal = "不支持的请求/操作";
                        break;
                    case 12:
                        requestCodeVal = "没有发现可用的打印机";
                        break;
                    case 13:
                        requestCodeVal = "设备/打印机没有被初始化";
                        break;
                    case 14:
                        requestCodeVal = "SDK没有被初始化";
                        break;
                    case 15:
                        requestCodeVal = "SDK的版本不匹配";
                        break;
                    case 16:
                        requestCodeVal = "对象已经存在";
                        break;
                    case 17:
                        requestCodeVal = "返回了无效的数据";
                        break;
                    default:
                }
            }
            return r;
        }

        // 入库扫描后打印面单  森
        @JavascriptInterface
        public void printOrderNew(String params){
            orderInfo = params;
            nReturnPrint = printFunNew();
            if (nReturnPrint == 0) {
                Log.d("LM", "打印成功");
//                AlertDialog.Builder builderw4 = new AlertDialog.Builder(mContext);
//                builderw4.setTitle("提示");
//                builderw4.setMessage("打印成功");
//                builderw4.show();
            }else{
                Log.d("LM", "打印失败");
                AlertDialog.Builder builderw4 = new AlertDialog.Builder(mContext);
                builderw4.setTitle("提示");
                builderw4.setMessage("打印失败" + requestCodeVal);
                builderw4.show();
            }
        }
        public int printFunNew(){
            JSONObject jo = JSON.parseObject(orderInfo);
            labelPrinter.SetPrintMode(1, 120);
            labelPrinter.SetPrintSpeed(14);
            int r = labelPrinter.SetLabelSize(640, 480);
            if (r != 0) {
                return r;
            }
            String font = "SIMSUN.TTF";

            String labelNo2 = jo.getString("labelNo"); //单号
            String omsNo = jo.getString("omsNo");  //格口
            String loc = jo.getString("loc");  //线体
//            String qty = "数量：" + jo.getString("qty");
//            String ydq = jo.getString("ydq");
            labelPrinter.PrintText(30, 70, font, labelNo2, 0, 20, 20, 2);
            labelPrinter.PrintBarcodeQR(250, 30, 0, labelNo2, 'H', 3, 2);
            labelPrinter.PrintText(30, 160, font, omsNo, 0, 50, 50, 2);
//            labelPrinter.PrintBarcodeQR(70, 250, 0, labelNo2, 'H', 4, 2) ;
            labelPrinter.PrintText(30, 270, font, loc, 0, 190, 190, 2);

//            labelPrinter.PrintText(330, 30, font, labelNo2, 0, 20, 20, 2);
//            labelPrinter.PrintText(85, 210, font, loc,  0, 80, 80, 2);
//            char[] chars = ydq.toCharArray();
//            int y = 110;
//            for (int i=0;i< chars.length;i++){
//                Log.d("LM", "000" + chars[i]+"");
//                labelPrinter.PrintText(520, y + i * 40, font, chars[i]+"",  0, 50, 50, 2);
//            }
//
//            labelPrinter.PrintText(30, 420, font, qty,  0, 30, 30, 2);
            r = labelPrinter.PrintLabel(1, 1);
            if (r != 0) {
                switch (r) {
                    case 1:
                        requestCodeVal = "无效的句柄";
                        break;
                    case 2:
                        requestCodeVal = "无效的参数";
                        break;
                    case 3:
                        requestCodeVal = "通讯错误";
                        break;
                    case 4:
                        requestCodeVal = "加载动态库失败";
                        break;
                    case 5:
                        requestCodeVal = "打开/创建文件失败";
                        break;
                    case 6:
                        requestCodeVal = "无效的路径";
                        break;
                    case 7:
                        requestCodeVal = "文件操作失败";
                        break;
                    case 8:
                        requestCodeVal = "内存操作失败";
                        break;
                    case 9:
                        requestCodeVal = "无效的内存";
                        break;
                    case 10:
                        requestCodeVal = "开辟的内存不足";
                        break;
                    case 11:
                        requestCodeVal = "不支持的请求/操作";
                        break;
                    case 12:
                        requestCodeVal = "没有发现可用的打印机";
                        break;
                    case 13:
                        requestCodeVal = "设备/打印机没有被初始化";
                        break;
                    case 14:
                        requestCodeVal = "SDK没有被初始化";
                        break;
                    case 15:
                        requestCodeVal = "SDK的版本不匹配";
                        break;
                    case 16:
                        requestCodeVal = "对象已经存在";
                        break;
                    case 17:
                        requestCodeVal = "返回了无效的数据";
                        break;
                    default:
                }
            }
            return r;
        }
        //
//        private String copyAssetGetFilePath(String fileName, Context context) {
//            try {
//                File cacheDir = context.getCacheDir();
//                if (!cacheDir.exists()) {
//                    cacheDir.mkdirs();
//                }
//                File outFile = new File(cacheDir, fileName);
//                if (!outFile.exists()) {
//                    boolean res = outFile.createNewFile();
//                    if (!res) {
//                        return null;
//                    }
//                } else {
//                    if (outFile.length() > 10) {//表示已经写入一次
//                        return outFile.getPath();
//                    }
//                }
//                InputStream is = context.getAssets().open(fileName);
//                FileOutputStream fos = new FileOutputStream(outFile);
//                byte[] buffer = new byte[1024];
//                int byteCount;
//                while ((byteCount = is.read(buffer)) != -1) {
//                    fos.write(buffer, 0, byteCount);
//                }
//                fos.flush();
//                is.close();
//                fos.close();
//                return outFile.getPath();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            return null;
//        }
        //    扫码
        @JavascriptInterface
        public void  VueSCAN() {

            new Thread() {
                public void run() {
                    Looper.prepare();//增加部分
                    IntentIntegrator integator = new IntentIntegrator(hbx.this);
                    integator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
                    integator.setPrompt("请扫描");
                    integator.setCameraId(0);
                    integator.setBeepEnabled(true); //扫描成功的「哔哔」声，默认开启
                    integator.setBarcodeImageEnabled(false);
                    integator.set_is_Continuous_Scan(false);
                    integator.setCaptureActivity(Scan_Single_Activity.class);
                    integator.initiateScan();

                }
            }.start();
        }

        // 播放警告音---震动+哔哔声
        @JavascriptInterface
        public void TipAudio() {
            Vibrator vibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
            long[] vibrationPattern = new long[]{1000,500,500,1000,500};
            vibrator.vibrate(vibrationPattern, -1);
            MediaPlayer mMediaPlayer = MediaPlayer.create(mContext, R.raw.wrong01);
            mMediaPlayer.start();
        }

        // 入库已到齐提示音
        @JavascriptInterface
        public void TipRuKuAudioYDQ() {
            MediaPlayer mMediaPlayer = MediaPlayer.create(mContext, R.raw.ydq);
            mMediaPlayer.start();
        }
        // 入库 错分件提示音
        @JavascriptInterface
        public void TipRuKuAudioCFJ() {
            MediaPlayer mMediaPlayer = MediaPlayer.create(mContext, R.raw.cfj);
            mMediaPlayer.start();
        }
        // 入库单价提示音
        @JavascriptInterface
        public void TipRuKuAudioDJ() {
            MediaPlayer mMediaPlayer = MediaPlayer.create(mContext, R.raw.dj);
            mMediaPlayer.start();
        }
        // 入库 订单已扫描提示音
        @JavascriptInterface
        public void TipRuKuAudioYSM() {

            MediaPlayer mMediaPlayer = MediaPlayer.create(mContext, R.raw.ysm);
            mMediaPlayer.start();
        }
        // 更新APP
        @JavascriptInterface
        public void UpDateApp(String url) {
            Log.d("LM", "更新APP111111111111111" + url);
            mClient.sendFileRequest(url, DestFileName);
        }

        // 连续扫码
        @JavascriptInterface
        public void ContinuousScan() {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    capture.is_Continuous_Scan = true;
                    capture.onResume();
                    scan_rt.setVisibility(View.VISIBLE);
                }
            });
        }

        // 取消连续扫码
        @JavascriptInterface
        public void CancelScan() {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

//                      android.view.ViewGroup.LayoutParams pp = scan_rt.getLayoutParams();
//                      pp.height = 80;
//                      scan_rt.setLayoutParams(pp);
                    scan_rt.setVisibility(View.INVISIBLE);
                    capture.onPause();
                }
            });
        }

        // 开启闪光灯
        @JavascriptInterface
        public void setTorchEnabled_true() {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    barcodeScannerView.setTorchOn();
                }
            });
        }

        // 关闭闪光灯
        @JavascriptInterface
        public void setTorchEnabled_false() {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    barcodeScannerView.setTorchOff();
                }
            });
        }

        @JavascriptInterface
        public  void updateAPP(){

            initHandler();
            checkVersion();
            ifManualUpdate = "手动更新";
        }
        /**
         * 极光推送设置别名
         * @param p
         */

        @JavascriptInterface
        public void setJPushAlias(String p) {
            JPushInterface.setAlias(mContext,0, p);
        }

    }
//    private MediaRecorder mRecorder;
//
//    private long mStartingTimeMillis;
//    private long mElapsedMillis;
//
//    // 开始录音
//    public void startRecording() {
////        setFileNameAndPath();
//
//        mRecorder = new MediaRecorder();
//        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
//        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); //录音文件保存的格式，这里保存为 mp4
////        mRecorder.setOutputFile(mFilePath); // 设置录音文件的保存路径
//        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
//        mRecorder.setAudioChannels(1);
//        // 设置录音文件的清晰度
//        mRecorder.setAudioSamplingRate(44100);
//        mRecorder.setAudioEncodingBitRate(192000);
//
//        try {
//            mRecorder.prepare();
//            mRecorder.start();
//            mStartingTimeMillis = System.currentTimeMillis();
//        } catch (IOException e) {
////            Log.e(LOG_TAG, "prepare() failed");
//        }
//    }

//    // 停止录音
//    public void stopRecording() {
//        mRecorder.stop();
//        mElapsedMillis = (System.currentTimeMillis() - mStartingTimeMillis);
//        mRecorder.release();
//
////        getSharedPreferences("sp_name_audio", MODE_PRIVATE)
////                .edit()
////                .putString("audio_path", mFilePath)
////                .putLong("elpased", mElapsedMillis)
////                .apply();
////        if (mIncrementTimerTask != null) {
////            mIncrementTimerTask.cancel();
////            mIncrementTimerTask = null;
////        }
//
//        mRecorder = null;
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(scanCodeBroadcastReceiver != null){
            unregisterReceiver(scanCodeBroadcastReceiver);
        }
    }

    private void initPermission() {

        Log.d("LM", "申请存储权限");

        try {

            if (Build.VERSION.SDK_INT>=23){
                if (MPermissionsUtil.checkAndRequestPermissions(hbx.this,
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,
                                Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.RECORD_AUDIO}
                        ,RequestPermission_STATUS_CODE0)){
                    checkVersion();
                }
            }else {

                checkVersion();
            }
        }catch (Exception e) {

            Log.d("LM", "initPermission: " + e.getMessage());
        }
    }

    public void checkVersion() {
        Log.d("LM", "检查apk及zip版本");

        Map<String, String> params = new HashMap<>();
//        params.put("param", null);
        params.put("params", AES256Utils.encrypt(Constants.SecretKey,"{\"tenantCode\":\"SFKC\"}"));

        //params.put("params","{\"tenantCode\":\"SFKC\"}");
        mClient.sendRequest(Constants.URL.SAAS_API_BASE + "kc-transport/tmsApp/queryAppVersion", params, TAG_CHECKVERSION);
    }

    private void initHandler() {

        mHandler=new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                int percent=message.arg1;
                if (percent==100){
                    createNotifaction(percent);
                    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),DestFileName);
                    if (!file.exists()) {

                        Toast.makeText(mContext, "升级包不存在", Toast.LENGTH_SHORT).show();
                    } else {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.addCategory(Intent.CATEGORY_DEFAULT);
                        Uri uri;
                        if (Build.VERSION.SDK_INT >= 24) {//android 7.0以上
                            uri =  FileProvider.getUriForFile(mContext, "com.cy_scm.android_sxjf2.fileprovider", file);
                        } else {
                            uri = Uri.fromFile(file);
                        }
                        String type = "application/vnd.android.package-archive";
                        intent.setDataAndType(uri, type);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        if (Build.VERSION.SDK_INT >= 24) {
                            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        }
                        startActivity(intent);
                    }
                    mNotificationManager.cancel(0);
                } else if (percent==-1) {

                    Toast.makeText(hbx.this, "更新失败，服务器异常", LENGTH_LONG).show();
                    mNotificationManager.cancel(0);
                } else{
                    createNotifaction(percent);
                }
                return false;
            }
        });
    }

    /**
     * 返回上一页
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            // 登录页时不允许返回上一页
            String curURL = mWebView.getUrl();
            String orgURL = mWebView.getOriginalUrl();
            if (curURL.equals("file:///android_asset/apps/H5A4057B2/www/index.html#/")) {

                Log.d("LM", "禁止返回上一页1：" + curURL);
                return true;
            }

            // 首页
            String Index = "file:///android_asset/apps/H5A4057B2/www/index.html#/Index";
            // 任务
            String Waybill = "file:///android_asset/apps/H5A4057B2/www/index.html#/Waybill";
            // 我的
            String HomeIndex = "file:///android_asset/apps/H5A4057B2/www/index.html#/HomeIndex";

            // 主菜单时不允许返回上一页
            if (
                    curURL.indexOf(Index + "?") != -1 || curURL.equals(Index) ||
                            curURL.indexOf(Waybill + "?") != -1 || curURL.equals(Waybill) ||
                            curURL.indexOf(HomeIndex + "?") != -1 || curURL.equals(HomeIndex)
            ) {

                Log.d("LM", "禁止返回上一页2：" + curURL);
                return true;
            }
            mWebView.goBack();
            return true;
        }
        return false;
    }


    /**
     * 创建下载进度的 notification
     * @param percent 下载进度
     */
    private void createNotifaction(int percent){
        //自定义 Notification 布局
        if (mUpdataNotification==null) {
            mUpdataNotification = new Notification();
            mUpdataNotification.icon =R.mipmap.ic_launcher;
            mUpdataNotification.tickerText =appName;
        }
        if (remoteView==null) {
            remoteView = new RemoteViews(mContext.getPackageName(), R.layout.dialog_download);
        }
        remoteView.setTextViewText(R.id.textView_dialog_download, percent+"%");
        remoteView.setProgressBar(R.id.progressBar_dialog_download, 100, percent, false);
        mUpdataNotification.contentView = remoteView;
        mNotificationManager.notify(0, mUpdataNotification);
    }

    @Override
    public void setProgressBarLoading(int progress) {
        // super.setProgressBarLoading(progress);
        //改为更新通知栏进度条
        Message message=mHandler.obtainMessage();
        message.arg1=progress;
        message.sendToTarget();
    }
    // android 7.0以上手机存储授权后回调
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {


        Log.d("LM", "拍照5.8: ");

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        Log.d("LM", "拍照5.9: ");

        if (requestCode == 101) {


            Log.d("LM", "拍照5.9.1: ");
            takeCameraM();
        }
        switch (requestCode) {
            case REQUEST_READ_PHONE_STATE:
                if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    //TODO
                }
                break;
            case 1:
                initPermission2();
                break;
            default:
                break;
        }
//
//        switch (requestCode) {
//            case 1://对应requestPermissions的requestCode
//                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {//如果一次申请多个权限，就按顺序依次grantResults[1]、grantResults[2]判断
////                    Toasts.showShort("再次点击即可拍照");
//                } else {
//                    // Permission Denied
//                }
//                break;
//        }
//
        if (requestCode==RequestPermission_STATUS_CODE0){
            for (int i=0;i<permissions.length;i++){
                if (grantResults[i]==PackageManager.PERMISSION_DENIED) {
                    switch (permissions[i]){
                        case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                            showToastMsg("请允许应用使用SD卡存储",3000);
                            showSnackbar("请允许应用使用SD卡存储~", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
//                                    Intent intent3 = new Intent(MainActivity.this, LoginActivity.class);
//                                    startActivity(intent3);
                                    AppContext.IS_LOGIN=false;
                                    finish();
                                }
                            },Snackbar.LENGTH_INDEFINITE);
                            break;
                        case Manifest.permission.CAMERA:
                            showToastMsg("请授权应用调用摄像头权限~",3000);
                            showSnackbar("请授权应用调用摄像头权限~", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Intent intent2=new Intent(Settings.ACTION_SETTINGS);
                                    startActivity(intent2);
                                }
                            },Snackbar.LENGTH_INDEFINITE);
                            break;
                        case Manifest.permission.ACCESS_COARSE_LOCATION:
                            showToastMsg("请授权应用网络定位和GPS定位权限ACCESS_COARSE_LOCATION",3000);
                            break;

                        case Manifest.permission.ACCESS_FINE_LOCATION:
                            showToastMsg("请授权应用网络定位和GPS定位权限ACCESS_FINE_LOCATION",3000);
                            break;

                        default:
                            showSnackbar("请授权应用网络定位和GPS定位权限", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Intent intent1=new Intent(Settings.ACTION_SETTINGS);
                                    startActivity(intent1);
                                }
                            },Snackbar.LENGTH_INDEFINITE);
                            break;
                    }
                    return;
                }
            }

        }
    }
    private String ALL = "all";
    private String CAMERA = "camera";
    private void openImageChooserActivity() {
        if (CAMERA.equals(imageChooserType)) {
            takeCamera();
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(hbx.this);
            builder.setTitle("拍照/相册");
            builder.setPositiveButton("相册", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    takePhoto();
                }
            });
            builder.setNegativeButton("拍照", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    takeCamera();
                }
            });
    //        builder.setNeutralButton("拍视频", new DialogInterface.OnClickListener() {
    //            @Override
    //            public void onClick(DialogInterface dialog, int which) {
    //                takeVideo();
    //            }
    //        });
            builder.setCancelable(false);
            builder.show();
        }
    }
    //选择图片
    private void takePhoto() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
//        i.setType("image/*");
        i.setType("*/*");
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
    }

    //拍照
    private void takeCamera() {
       /* String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_"+timeStamp+"_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File imageFile;
        try {

            imageFile = File.createTempFile(imageFileName,".jpg",storageDir);
            cameraFielPath = imageFile.getPath();
        } catch (IOException e) {

            e.printStackTrace();
        }

        File cameraPhoto = new File(cameraFielPath);
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri photoUri = FileProvider.getUriForFile(
                this,
                "com.cy_scm.tms_android.fileprovider",
                cameraPhoto);
        takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        startActivityForResult(takePhotoIntent, FILE_CAMERA_RESULT_CODE);


*/
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        if (hasSDCard()) {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName = "JPEG_"+timeStamp+"_";
            File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            File imageFile;
            imageFile = new File(storageDir, imageFileName + ".jpg");
            //第二个参数需要和 AndroidManifest.xml 中的android:authorities 保持一致
            cameraFielUri = FileProvider.getUriForFile(mContext, "com.cy_scm.android_sxjf2.fileprovider", imageFile);
            Log.d("LM", "contentUri = " + cameraFielUri);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraFielUri);
            startActivityForResult(intent, FILE_CAMERA_RESULT_CODE);
//            try {
//
//                imageFile = File.createTempFile(imageFileName,".jpg",storageDir);
//                cameraFielPath = imageFile.getPath();
//            } catch (IOException e) {
//
//                e.printStackTrace();
//            }
//            File outputImage = new File(cameraFielPath);
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outputImage));
//            startActivityForResult(intent, FILE_CAMERA_RESULT_CODE);
        }
    }

    // 拍视频
    private void takeVideo() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

        if (hasSDCard()) {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName = "JPEG_"+timeStamp+"_";
            File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            File imageFile;
            imageFile = new File(storageDir, imageFileName + ".mp4");
            //第二个参数需要和 AndroidManifest.xml 中的android:authorities 保持一致
            cameraFielUri = FileProvider.getUriForFile(mContext, "com.cy_scm.android_sxjf2.fileprovider", imageFile);
            Log.d("LM", "contentUri = " + cameraFielUri);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraFielUri);
            startActivityForResult(intent, FILE_CAMERA_RESULT_CODE);
        }
    }

    /**
     * 判断手机是否有SD卡。
     *
     * @return 有SD卡返回true，没有返回false。
     */
    public boolean hasSDCard() {

        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    private void takeCameraM() {
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//打开相机的Intent
        if(takePhotoIntent.resolveActivity(getPackageManager())!=null){//这句作用是如果没有相机则该应用不会闪退，要是不加这句则当系统没有相机应用的时候该应用会闪退
            File imageFile = createImageFile();//创建用来保存照片的文件
            if(imageFile!=null){
                if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
//                    7.0以上要通过FileProvider将File转化为Uri
                    mImageUri = FileProvider.getUriForFile(this,FILE_PROVIDER_AUTHORITY,imageFile);
                }else {
//                    7.0以下则直接使用Uri的fromFile方法将File转化为Uri
                    mImageUri = Uri.fromFile(imageFile);
                }
                takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT,mImageUri);//将用于输出的文件Uri传递给相机
                startActivityForResult(takePhotoIntent, FILE_CAMERA_RESULT_CODE);//打开相机
            }
        }else {
        }
    }

    /**
     * 创建用来存储图片的文件，以时间来命名就不会产生命名冲突
     * @return 创建的图片文件
     */
    private File createImageFile() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_"+timeStamp+"_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File imageFile = null;
        try {
            imageFile = File.createTempFile(imageFileName,".jpg",storageDir);
            cameraFielPath = imageFile.getPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageFile;
    }

    /**
     * 判断文件是否存在
     */
    public static boolean hasFile(String path) {
        try {
            File f = new File(path);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {

            return false;
        }
        return true;
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(Intent intent) {
        Uri[] results = null;
        if (intent != null) {
            String dataString = intent.getDataString();
            ClipData clipData = intent.getClipData();
            if (clipData != null) {
                results = new Uri[clipData.getItemCount()];
                for (int i = 0; i < clipData.getItemCount(); i++) {
                    ClipData.Item item = clipData.getItemAt(i);
                    results[i] = item.getUri();
                }
            }
            if (dataString != null)
                results = new Uri[]{Uri.parse(dataString)};
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        capture.onPause();
        capture.onResume();

        Log.d("LM", "onActivityResult: ----");

        IntentResult intentresult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);

        if (intentresult != null) {

            if (intentresult.getContents() == null) {

                Toast.makeText(this, "已返回", LENGTH_LONG).show();
            } else {

//                Toast.makeText(this, intentresult.getContents(), LENGTH_LONG).show();
                String url = "javascript:QRScanAjax('" + intentresult.getContents() + "')";
                hbx.mWebView.loadUrl(url);

                Log.d("LM", url);
                Log.d("LM", hbx.this.inputName);
            }

        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }

        super.onActivityResult(requestCode, resultCode, data);

        if (null == uploadMessage && null == uploadMessageAboveL) return;

        if (resultCode != RESULT_OK) {//同上所说需要回调onReceiveValue方法防止下次无法响应js方法

            if (uploadMessageAboveL != null) {
                uploadMessageAboveL.onReceiveValue(null);
                uploadMessageAboveL = null;
            }
            if (uploadMessage != null) {
                uploadMessage.onReceiveValue(null);
                uploadMessage = null;
            }
            return;
        }

        Uri result = null;
        if (requestCode == FILE_CAMERA_RESULT_CODE) {

//            if (result == null && hasFile(cameraFielPath)) {
//
//                result = Uri.fromFile(new File(cameraFielPath));
//            }
            if (result == null && cameraFielPath != null && hasFile(cameraFielPath)) {

                result = Uri.fromFile(new File(cameraFielPath));
            }
            if( cameraFielUri != null){
                result = cameraFielUri;
            }
            if (uploadMessageAboveL != null) {

                uploadMessageAboveL.onReceiveValue(new Uri[]{result});

                uploadMessageAboveL = null;
            } else if (uploadMessage != null) {

                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        } else if (requestCode == FILE_CHOOSER_RESULT_CODE) {

            if (data != null) {
                result = data.getData();
            }
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }
    }
    private void setPermissions() {
        if (ContextCompat.checkSelfPermission(hbx.this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,PERMISSION,1);
//            ActivityCompat.requestPermissions(this, Manifest.permission.CAMERA); 1111111111111111111111
//            ActivityCompat.requestPermissions(hbx.this, new String[]{Manifest.permission.CAMERA}, RequestPermission_STATUS_CODE0);
//            ActivityCompat.requestPermissions(hbx.this, Manifest.permission.CAMERA, '');
            ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA);
        }else{
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA
            },0);
            Log.i("TAG","setPermissions ok");
        }
    }
    private void initPermission2() {
        List<String> mPermissionList = new ArrayList<>();
        // Android 版本大于等于 12 时，申请新的蓝牙权限
        if (Build.VERSION.SDK_INT >= 31) {
         mPermissionList.add("android.permission.BLUETOOTH_SCAN"); // Manifest.permission.BLUETOOTH_SCAN
         mPermissionList.add("android.permission.BLUETOOTH_ADVERTISE"); // Manifest.permission.BLUETOOTH_ADVERTISE
         mPermissionList.add("android.permission.BLUETOOTH_CONNECT"); //  Manifest.permission.BLUETOOTH_CONNECT

            //根据实际需要申请定位权限
            //mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            //mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        } else {
            mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }

        ActivityCompat.requestPermissions(this, mPermissionList.toArray(new String[0]), 3);
    }
    /**
     * 初始化极光推送
     */
    private void initJPush() {
        JPushInterface.setDebugMode(true);
        JPushInterface.init(mContext.getApplicationContext());
    }

}